var PAGE_MAP_VIEW = "map-view";
var PAGE_BOILER_VIEW = "boiler-view";
var PAGE_CALCULATE_DATA_VIEW = "calculate-data-view";
var PAGE_MENU_VIEW = "menu-view";
var PAGE_MAIL_VIEW = "mail-view";

function InitView(currentPage) {
    if (currentPage == PAGE_MAP_VIEW) {
        var lat = 10.7253272;
        var lon = 106.6175712;
        // OpenStreetMapUtil.setDefaultVariable();
        // OpenStreetMapUtil.initMap("map-canvas",lon,lat);
        // OpenStreetMapUtil.setMapCenter(lon,lat);
        router.currentView.mapViewer = new OpenStreetMap();
        router.currentView.mapViewer.initMap("map-canvas", lon, lat);
        router.currentView.mapViewer.setMapCenter(lon, lat);

        // start set innit location
        var param = '' || {};
        var mapEventClickMarkerhandle = function(evt) {
            OpenLayers.Event.stop(evt);
        };

        var paramMarkerPopup = {};
        // paramMarkerPopup['boilerId'] = boiler.boilerId;
        paramMarkerPopup['lon'] = lon;
        paramMarkerPopup['lat'] = lat;
        paramMarkerPopup['popupContentHTML'] = Util.getPopupContentHTMLMapV2();
        paramMarkerPopup['imgUrl'] = IconUtil.getMapMarkerAlartIcon();
        paramMarkerPopup['mapEventClickMarkerhandle'] = mapEventClickMarkerhandle;
        paramMarkerPopup['closeBox'] = false;
        paramMarkerPopup['overflow'] = false;
        paramMarkerPopup['deviceId'] = "gps_test";
        router.currentView.mapViewer.setMarkerPopup(paramMarkerPopup);
        // end set innit location

        $("#selectIcons").select2();
        $("#selectMapsSize").select2();
        $("#selectMarkers").select2();
        $("#selectMarkers").on("change", function(e) {
            var idMarker = $("#selectMarkers option:selected").val();
            var txtIdBoiler = $('#boiler_id');
            txtIdBoiler.val(idMarker);
        }).trigger("change");

        $("#selectMapsSize").on("change", function(e) {
            var sizeMapsData = $("#selectMapsSize option:selected").val();
            if (sizeMapsData != "-1") {
                var sizeMaps = sizeMapsData.split(",");
                $("#map-canvas").css("width", sizeMaps[0]);
                $("#map-canvas").css("height", sizeMaps[1]);

                var lat = 10.7253272;
                var lon = 106.6175712;
                // OpenStreetMapUtil.setDefaultVariable();
                // OpenStreetMapUtil.initMap("map-canvas",lon,lat);
                // OpenStreetMapUtil.setMapCenter(lon,lat);
                router.currentView.mapViewer.clearContainer();
                router.currentView.mapViewer.gc();
                router.currentView.mapViewer = new OpenStreetMap();
                router.currentView.mapViewer.initMap("map-canvas", lon, lat);
                router.currentView.mapViewer.setMapCenter(lon, lat);
            }
            return false;
        }).trigger("change");

        autoLoad();
    } else if (currentPage == PAGE_BOILER_VIEW) {

    } else if (currentPage == PAGE_CALCULATE_DATA_VIEW) {

    } else if (currentPage == PAGE_MENU_VIEW) {
        gridster = undefined;
        GridsterUtil.newGridster();
        initDashboard();
        // GridsterUtil.addContainer(500,500,1,1);

    } else if (currentPage == PAGE_MAIL_VIEW) {
//        var canvasId = 'canvas-a2bce3434';
//        var kPixelWidth = 256;
//        var kPixelHeight = 256;
//        var kPieceWidth = 10;
//        var kPieceHeight = 10;
//        var headerPadding = 12;
//        var canvas = document.createElement('canvas');
//        canvas.id = canvasId;
//        canvas.width = kPixelWidth;
//        canvas.height = kPixelHeight;
//        function getMousePos(canvas, evt) {
//            var x;
//            var y;
//            if (evt.pageX != undefined && evt.pageY != undefined) {
//                x = evt.pageX;
//                y = evt.pageY;
//            } else {
//                x = evt.clientX + document.body.scrollLeft +
//                        document.documentElement.scrollLeft;
//                y = evt.clientY + document.body.scrollTop +
//                        document.documentElement.scrollTop;
//            }
//            
//            x -= canvas.offsetLeft;
//            y -= canvas.offsetTop;
//            
//            var cell = {
//                    col : Math.floor(y/kPieceHeight),
//                    row : Math.floor(x/kPieceWidth)
//            };
//            
//            var rect = canvas.getBoundingClientRect();
//            return {
//              x: evt.clientX - rect.left,
//              y: evt.clientY - rect.top
//            };
//        }
////        function writeMessage(canvas, message) {
////            var context = canvas.getContext('2d');
////            context.clearRect(0, 0, canvas.width, canvas.height);
////            context.font = '18pt Calibri';
////            context.fillStyle = 'black';
////            context.fillText(message, 10, 25);
////        }
////        canvas.addEventListener('mousemove', function(evt) {
////            var mousePos = getMousePos(canvas, evt);
////            var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
////            writeMessage(canvas, message);
////        }, false);
//        function gridLinesCanvas(canvas){
//            var context = canvas.getContext('2d');
////            context.clearRect(0, 0, kPixelWidth, kPixelHeight);
//            context.beginPath();
//
//            /* vertical lines */
//            for (var x = 0; x <= kPixelWidth; x += kPieceWidth) {
//                context.moveTo(0.5 + x, 0);
//                context.lineTo(0.5 + x, kPixelHeight);
//            }
//
//            /* horizontal lines */
//            for (var y = 0; y <= kPixelHeight; y += kPieceHeight) {
//                context.moveTo(0, 0.5 + y);
//                context.lineTo(kPixelWidth, 0.5 +  y);
//            }
//
//            /* draw it! */
//            context.strokeStyle = "#ccc";
//            context.stroke();
//            context.closePath();
//        }
//        var container = document.getElementById("sub-container");
//        container.appendChild(canvas);
//        
//        var canvasObj = document.getElementById(canvasId);
//        
//        var ctx = canvasObj.getContext('2d');
//        
////        var warningText = 'warning';
////        ctx.font = "bold 24px sans-serif";
////        
////        ctx.fillStyle = '#000066';
////        ctx.textAlign = 'right';
////        ctx.fillText(warningText,  28, 43);
//        var radius = 10;
//        ctx.beginPath();
//        ctx.arc(50, 50, radius, 0, 2 * Math.PI, false);
//        ctx.fillStyle = 'green';
//        ctx.closePath();
//        ctx.fill();
//        canvas.addEventListener('click', function(evt) {
//            var mousePos = getMousePos(canvas, evt);
//            var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
//            var distance = Math.sqrt(Math.pow(50 - mousePos.x, 2) + Math.pow(50 - mousePos.y, 2));
//            distance <= radius ? console.log('inside circle') : console.log('ounner circle');
//            if(distance <= radius){
//                var ctx = canvas.getContext('2d');
//                ctx.clearRect(0, 0, canvas.width, canvas.height);
//                ctx.beginPath();
//                ctx.arc(50, 50, radius, 0, 2 * Math.PI, false);
//                ctx.fillStyle = 'black';
//                ctx.closePath();
//                ctx.fill();
//                gridLinesCanvas(canvas);
//            } else {
//                var ctx = canvas.getContext('2d');
//                ctx.clearRect(0, 0, canvas.width, canvas.height);
//                ctx.beginPath();
//                ctx.arc(50, 50, radius, 0, 2 * Math.PI, false);
//                ctx.fillStyle = 'green';
//                ctx.closePath();
//                ctx.fill();
//                gridLinesCanvas(canvas);
//            }
//           
//        }, false);
//        gridLinesCanvas(canvas);
//        
//        var sun = new Image();
//        var moon = new Image();
//        var earth = new Image();
//        
//        sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
//        moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
//        earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
//        window.requestAnimFrame = (function(callback) {
//            return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
//            function(callback) {
//              window.setTimeout(callback, 1000 / 60);
//            };
//        })();
////        window.requestAnimationFrame(draw);
//        requestAnimFrame(function() {
//            draw();
//        });
//        function draw() {
//            var ctx = canvas.getContext('2d');
//            ctx.clearRect(0, 0, kPixelWidth, kPixelHeight);
//
//            ctx.globalCompositeOperation = 'destination-over';
//
//            ctx.fillStyle = 'rgba(0,0,0,0.4)';
//            ctx.strokeStyle = 'rgba(0,153,255,0.4)';
//            ctx.save();
//            ctx.translate(150,150);
//
//            // Earth
//            var time = new Date();
//            ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
//            ctx.translate(105,0);
//            ctx.fillRect(0,-12,50,24); // Shadow
//            ctx.drawImage(earth,-12,-12);
//
//            // Moon
//            ctx.save();
//            ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );
//            ctx.translate(0,28.5);
//            ctx.drawImage(moon,-3.5,-3.5);
//            ctx.restore();
//
//            ctx.restore();
//            
//            ctx.beginPath();
//            ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit
//            ctx.stroke();
//           
//            ctx.drawImage(sun,0,0,300,300);
//
////            window.requestAnimationFrame(draw);
//            requestAnimFrame(function() {
//                draw();
//            });
//          }
        
        var state = new CanvasState('',{});
        state.init();
        
//        function doAsync03(timeOuts){
//            var deferredObject = $.Deferred();
//            
//            setTimeout(function() {
//                console.log(deferredObject.state());
//                var state = deferredObject.state();
//
//                console.log('write line 03');
//                console.log("Executed after a delay " + timeOuts + "ms");
//                deferredObject.resolve('resolve 03');
//
//            }, timeOuts);
//            
//            return deferredObject;
//        };
        
        
        var div = $('#promise');
//        
//        function fn1(){
//            div.append('1 </br>');
//        }
//        
//        function fn2(){
//            div.append('2 </br>');
//        }
//        
//        function fn3(){
//            div.append('3 </br>');
//        }
//        
//        var dfd = $.Deferred();
//        
//        dfd.done( fn1,fn2,fn3 )
//        .done(function( result ) {
//            div.append( result + " we're done. </br>" );
//        });
//        
//        $("button").on( "click", function() {
//            dfd.resolve( "all" );
//        });
        
        function doWorkAfter(timeOuts,work){
            return $.Deferred(function(deferredObject) {
                setTimeout(function(){
                   
                    if(work === '02'){
//                        deferredObject.reject('resolve fail ' + work);
                        setTimeout(function(){
                            console.log('write line ' + work);
                            div.append('write line '+ work +'</br>');
                            deferredObject.resolve('resolve ' + work);
                        }, timeOuts);
                    }else if(work === '04'){
                        
                        setTimeout(function(){
                            deferredObject.reject('resolve fail ' + work);
                        }, 10000);
                       
                    }else{
                        console.log('write line ' + work);
                        div.append('write line '+ work +'</br>');
                        deferredObject.resolve('resolve ' + work);
                    }
                    
                }, timeOuts);
            }).promise();
        };
        
        $("button").on( "click", function() {
            $("button").hide();
            div.html('');
            div.append('Ready...</br>');
//            console.log('write line 01');
//            div.append('write line 01 </br>');
//            console.log('write line 02');
//            div.append('write line 02 </br>');
////            console.log('write line 03');
//            
//            var work03 = doWorkAfter(1000,'00').done(function(result){
//                console.log(result);
//                div.append(result + '</br>');
//            }).fail(function(result){
//                console.log(result);
//                console.log('on work after not print !!');
//                div.append(result + '</br>');
//                div.append('on work after not print !! </br>');
//            });
//            
//            work03.then(function(){
//                console.log('write line 04 </br>');
//                console.log('write line 05 </br>');
//                div.append(result);
//            });
            
            var work01 = doWorkAfter(1000,'01').done(function(result){
                console.log(result);
                div.append(result + '</br>');
            }).fail(function(result){
                $("button").show();
                div.append(result + '</br>');
            });
            var work02 = work01.then(function(){
                doWorkAfter(1000,'02').done(function(result){
                    console.log(result);
                    div.append(result + '</br>');
                }).fail(function(result){
                    $("button").show();
                    div.append(result + '</br>');
                });
            });
            
            var work03 = work02.then(function(){
                doWorkAfter(1000,'03').done(function(result){
                    console.log(result);
                    div.append(result + '</br>');
                }).fail(function(result){
                    $("button").show();
                    div.append(result + '</br>');
                });
            });
            
            var work04 = work03.then(function(){
                var work04 = doWorkAfter(1000,'04').done(function(result){
                    console.log(result);
                    div.append(result + '</br>');
                }).fail(function(result){
                    $("button").show();
                    div.append(result + '</br>');
                });
            });
            
//            work01.then(function(){
//                var work02 = doWorkAfter(1000,'02').done(function(result){
//                    console.log(result);
//                    div.append(result + '</br>');
//                }).fail(function(result){
//                    $("button").show();
//                    div.append(result + '</br>');
//                });
//            });
//                work02.then(function(){
//                    var work03 = doWorkAfter(1000,'03').done(function(result){
//                        console.log(result);
//                        div.append(result + '</br>');
//                    }).fail(function(result){
//                        $("button").show();
//                        div.append(result + '</br>');
//                    });
//                    
//                    work03.then(function(){
//                        var work04 = doWorkAfter(1000,'04').done(function(result){
//                            console.log(result);
//                            div.append(result + '</br>');
//                        }).fail(function(result){
//                            $("button").show();
//                            div.append(result + '</br>');
//                        });
//                        
//                        work04.then(function(){
//                            var work05 = doWorkAfter(1000,'05').done(function(result){
//                                console.log(result);
//                                $("button").show();
//                                div.append(result + '</br>');
//                            }).fail(function(result){
//                                $("button").show();
//                                div.append(result + '</br>');
//                            });
//                        });
//                    });
//                });
//            });
           
        });
        
 
//        doAsync03(1000).done(function (value) {
//            console.log("Executed doAsync03 succeeded ");
//            console.log(value);
//            console.log('write line 04');
//            console.log('write line 05');
//            console.log('write line 06');
//            console.log('write line 07');
//            console.log('write line 08');
//        }).fail(function(value) {
//            console.log("Executed doAsync03 fail ");
//            console.log(value);
//        }).always(function(value) {
//            console.log("Always callback function");
//            console.log(value);
//        });
       
       
    }
};